<?php

namespace app\api\controller;

use app\common\model\UserModel;
use app\common\model\Service;
use fast\Random;
use think\facade\Config;
use think\facade\Validate;
use app\common\library\Ems;
use app\common\library\Sms;
use think\facade\Db;
use app\common\controller\Api;
use app\common\model\Order;
use app\api\wappay\AlipayTradeWapPayContentBuilder;
use app\api\wappay\AlipayTradeService;

/**
 * 支付宝支付接口.
 */
class Alindex extends Api
{
    protected $noNeedLogin = ['writeLog','propssent','alipay','alipaynotifyurl','login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

        //支付宝网关
    public  $gatewayUrl = "https://openapi.alipay.com/gateway.do";
        //应用ID
    public $appId = "2021001144613411";
        //支付宝公钥
    public $alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmfW7vg4fJTMeOHj3wHxSMqte662SYMy5Nrdx2N/QhcUaGxWWkeAlF/GshSN65mVcf7rM5SXo1XHDHzEwTEbRuQgprGncp+ZKCuLyegv8oVhmLX7gdlU3wx922GyNftv1gvRnWiVFOLIPS5yO8mc6N1niC874kO3mZyWTrO4h8OO1zmujWyv8uecVLO5niThiN2PX1K3WY7xt8VKGiuVHBrVg9OAyBacraKVYRY8Yz1BfaIgw8vzwhnyFyMwMBOoaYomPw1PSaVPX3hE68znRHUNhJarAS7jH682lVU/uOXjLfKB3FkK4O3Lew0gWgLoLgoHc1AUAxoY+bAyXOKyx/wIDAQAB";
        //商户私钥
    public $merchant_private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCI4rZFstZqhlSujSt93Il62PyeKIgGhfciz+ia0G5RImZWWueCmQkkAxC/qEesWKm/aRfBxT97Ympdhlg4qwPRZSCqAkCMN7foTbefNeTny7Kc1QM8M7DxDavYzvCEjsrWriBT8HBtlT7IYzXbpsd+7VLq4V4TN40KVTouMPDsf211tnXotKbGKgnbVSqiiGBsxjp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VHG/1CHPH659ed0a9WXhEbi4pujGBvYmUhuZvriJ0L9wjfvYCfhigB/ZbkgkQ0rAEtah7tyGeOW5ZVC9Ebt1bcKKDu7kPnG6qNk61S0Xe7YAyLaUNPAhaVAoGASI313bVoQgbKMCtW4TneIhlR+u5Z8X+8mRibjBpmWLI+vPup40C5hkXjGTyIWiiu+6lM+/mUho5QU7m3rMM8vndH7HATTwNhPrO2LKl8vLWD6OS2Bs1gxtiCXFvZ4uLjBLLWtvlVZGQV3Y05AB6KUW/bxdHq3Q9PGhYoqyZ2+SU=";
        //异步通知地址
    public $notify_url = 'http://47.96.128.147/api/alindex/alipaynotifyurl';
        //同步跳转
    public $return_url = 'http://47.96.128.147/index/index/filish';
        //编码格式
    public $charset = 'UTF-8';
        //签名方式
    public $sign_type = 'RSA2';
    /**
     * 获取单号
     */
    public function NumRule($prefix='DH')
    {
        return $prefix.date('YmdHis',time()).mt_rand(1000, 9999);
    }

    /**
     * 支付宝手机网站支付接口
     */
    public function alipay()
    {
        $param = $this->request->param();
        
        $config = array ('app_id' => $this->appId,'merchant_private_key' => $this->merchant_private_key,'notify_url' => $this->notify_url,'return_url' => $this->return_url,'charset' => "UTF-8",'sign_type'=>"RSA2",'gatewayUrl' => $this->gatewayUrl,'alipay_public_key' => $this->alipay_public_key,);


        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $param['order_no'];
        //订单名称，必填
        $subject = '元宝充值';
        //付款金额，必填
        $total_amount = $param['price'];
//        $total_amount = 0.01;
        //商品描述，可空
        $body = '元宝充值';
        //超时时间
        $timeout_express="1m";
        //拉起支付
        $payRequestBuilder = new AlipayTradeWapPayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setOutTradeNo($out_trade_no);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setTimeExpress($timeout_express);

        $payResponse = new AlipayTradeService($config);
        $result=$payResponse->wapPay($payRequestBuilder,$config['return_url'],$config['notify_url']);
    }

    /**
     * 支付宝异步支付通知地址
     */
    public function alipaynotifyurl()
    {
//        $json = '{"gmt_create":"2021-07-13 21:48:38","charset":"UTF-8","seller_email":"admin@77yuewan.com","subject":"\u5143\u5b9d\u5145\u503c","sign":"NI5Z2xtrYqwqGFD96UHP4QFuDWmoADlUzs99HMLaLwE5WBIl1bnAG6jEdADjAWHD3rahDVhBI8JC4\/gvVZq\/0QZrQkShQyqig3nM7x2QGXpTcK5HSttzmNCRxVuCA\/CwEd6T0w4qJY\/1v\/klIK0YVchn29IGh+Cofqq7XR7hUDdCpOIjwsr29\/PP48y6Ub7xTICqQ5BQedAJMcKzQKDBzcfcmWCWNMo6X5WB802GFpcCKFwEtgEiGIhQnE7U8eqR2shqgZqFBH1Dtr\/iDBIZ+SeLoGwQTWiX4STO4PFjazYqO8Gdm4Js6uE1S7gZ751e+WOPdIGNrS5QQEc+jtLXcQ==","body":"\u5143\u5b9d\u5145\u503c","buyer_id":"2088802886202970","invoice_amount":"0.01","notify_id":"2021071300222214839002971407198326","fund_bill_list":"[{\"amount\":\"0.01\",\"fundChannel\":\"ALIPAYACCOUNT\"}]","notify_type":"trade_status_sync","trade_status":"TRADE_SUCCESS","receipt_amount":"0.01","buyer_pay_amount":"0.01","app_id":"2021001144613411","sign_type":"RSA2","seller_id":"2088731600002298","gmt_payment":"2021-07-13 21:48:39","notify_time":"2021-07-13 21:48:40","version":"1.0","out_trade_no":"CZ202107132148327711","total_amount":"0.01","trade_no":"2021071322001402971453165568","auth_app_id":"2021001144613411","buyer_logon_id":"451***@qq.com","point_amount":"0.00"}';
//        $arr = json_decode($json,true);
        //验签
        $arr=$_POST;
        Db::table('ik_test')->insert(['a'=>json_encode($_POST)]);
        $config = array ('app_id' => $this->appId,'merchant_private_key' => $this->merchant_private_key,'notify_url' => $this->notify_url,'return_url' => $this->return_url,'charset' => "UTF-8",'sign_type'=>"RSA2",'gatewayUrl' => $this->gatewayUrl,'alipay_public_key' => $this->alipay_public_key,);
        $alipaySevice = new AlipayTradeService($config);
        $alipaySevice->writeLog(var_export($_POST,true));
        $result = $alipaySevice->check($arr);
        if($result) {//验签成功
            if($this->appId != $arr['app_id']){echo "fail";exit;} //验证app_id是否为该商户本身
            if($arr['trade_status'] == 'TRADE_FINISHED') {
                //交易完结
            }else if ($arr['trade_status'] == 'TRADE_SUCCESS') {
                //查找当前订单是否存在
                $where['order_no'] = $arr['out_trade_no'];
                $res = Order::get($where);
//                dd($res);
                //订单存在则对比金额是否修改
//                if(!empty($res) && $res['price'] == $arr['total_amount']){

                if(!empty($res)){
                    //支付成功修改支付状态及更新信息
                $data['extra'] = json_encode($arr); //订单备注信息 json格式',
                $data['payment_no'] = $arr['trade_no']; //支付流水号
                $data['pay_type'] = 1; //支付类型 1:支付宝 2:微信',
                    $data['status'] = 1; //0:未支付 1:已支付 2:已关闭
                $data['update_time'] = strtotime($arr['gmt_payment']); //支付时间
                Order::update($data,$where);
                    //成功后访问游戏发送道具接口  103.39.222.108/gm/chongzhi.php
                    $this->propssent($arr['total_amount'],$res['actorid'],$res['service_id']);
//                    $this->propssent($res['price'],$res['actorid'],$res['service_id']);

                    $user=(new UserModel())->find($res['user_id']);
                    $user->recharge=$user->recharge+$arr['total_amount'];
                    $user->save();
                }

            }
            echo "success";
        }else {
            //验证失败
            echo "fail";
        }
    }

    /**
     * 成功后访问游戏发送道具接口 103.39.222.108/gm/chongzhi.php
     * total_amount  充值金额 * 100 = 元宝数量
     * actorid  角色id
     * sub 请求类型  cz 表示充值
     * service 大区id
     */
    public function propssent($total_amount,$actorid,$service)
    {
        //元宝数量
        $num = $total_amount * 100;
        //获取大区ip
        $where['id'] = $service;
        $arr = Service::get($where);
        if(!empty($arr)){
            $server_ip = $arr['server_ip'];
        }else{
            return false;
        }
        //开始请求
        $url = "http://182.92.111.3/gm/chongzhi.php";
        $data = array('actorid'=>$actorid,'sub'=>'cz','num'=>$num,'service'=>$service,'ip'=>$server_ip);
        $result =$this->curl_post($url,$data);
        return $result;
    }
    /*
     * 发送一个post请求
     */
    public function curl_post( $url,$postdata)
    {
        $this->apiwriteLog('发道具接口请求数据'.json_encode($postdata),'fadaoju');
        $header = array(
            'Accept: application/json',
        );
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // 超时设置
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        // 超时设置，以毫秒为单位
        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);
        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE );
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
        //执行命令
        $data = curl_exec($curl);
        curl_close($curl);
        $this->apiwriteLog('发道具接口返回数据'.$data,'fadaoju');
        return $data;
    }
    /*
     * 写入日志
     * text 日志内容
     * name 日志文件名
     */
    public function apiwriteLog($text,$name)
    {
        // $text=iconv("GBK", "UTF-8//IGNORE", $text);
        //$text = characet ( $text );
        file_put_contents ( dirname ( __FILE__ ).DIRECTORY_SEPARATOR."./../../".$name.".txt", date ( "Y-m-d H:i:s" ) . "  " . $text . "\r\n", FILE_APPEND );
    }
}
